const bindAll = require('lodash.bindall');
const PropTypes = require('prop-types');
const React = require('react');
const connect = require('react-redux').connect;

import loginCSS from './login.css';

class Login extends React.Component {
    constructor (props) {
        super(props);

        this.state = {
            un:'',//账号
            pw:'',//密码
            waiting: false
        };
        bindAll(this, [
            'handleUNChange',
            'handlePWChange',
            'handleSubmit'
        ]);
    }

    handleUNChange (e) {this.setState({un: e.target.value});}
    handlePWChange (e) {this.setState({pw: e.target.value});}
    handleSubmit () {
        //检查账号格式：数字、大小写字母，长度：6~16
        var reg = /^(?:\d+|[a-zA-Z]+){6,16}$/;
        if (!reg.test(this.state.un)) {
            alert("账号格式不正确!");
            return
        }
        //检查密码格式：
        reg = /^(?:\d+|[a-zA-Z]+|[!@#$%^&*]+){6,16}$/;
        if (!reg.test(this.state.pw)){
            alert("密码格式不正确!");
            return
        };

        this.setState({waiting: true});
        this.props.onLogIn(
            `un=${this.state.un}&pw=${this.state.pw}`, 
            () => {this.setState({waiting: false});}
        );
    }
    render () {
        return (
            <div className={loginCSS.login}>
                <input
                    required
                    type="text"
                    placeholder="账号"
                    maxLength="16"
                    onChange={this.handleUNChange}
                />

                <input
                    required
                    type="password"
                    placeholder="密码"
                    maxLength="16"
                    onChange={this.handlePWChange}
                />                                            

                <div className={loginCSS.submitRow }>
                    {this.state.waiting ?(<div>登录中...</div>):(
                        <button 
                            className={loginCSS.submitButton}
                            onClick={this.handleSubmit}
                        >
                        登 录
                        </button>
                    )}

                    <a href="/user/login" target="_blank">注 册</a>
                </div>

            </div>
       );
    }
}

Login.propTypes = {
    onLogIn: PropTypes.func
};
const mapStateToProps = state => ({});
const mapDispatchToProps = () => ({});
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Login);
